package com.mall.common.directive;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.mall.b2c.Setting;
import com.mall.b2c.hessian.CacheService;

import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModel;

/**
 * 处理货币精度标签
 *
 */
@Repository
public class CurrencyMethod implements TemplateMethodModel {
	@Resource private CacheService cacheService;

	@SuppressWarnings("rawtypes")
	public Object exec(List arguments) {
		if (arguments != null && !arguments.isEmpty() && arguments.get(0) != null && 
				StringUtils.isNotEmpty(arguments.get(0).toString())) {
			boolean flag = false;
			boolean flag1 = false;
			if (arguments.size() == 2) {
				if (arguments.get(1) != null)
					flag = Boolean.valueOf(arguments.get(1).toString()).booleanValue();
			} else{
				if (arguments.size() > 2) {
					if (arguments.get(1) != null)
						flag = Boolean.valueOf(arguments.get(1).toString()).booleanValue();
					if (arguments.get(2) != null)
						flag1 = Boolean.valueOf(arguments.get(2).toString()).booleanValue();
				}
			}
			Setting setting = cacheService.getSystemConfig();
			BigDecimal bigdecimal = new BigDecimal(arguments.get(0).toString());
			String s = setting.setScale(bigdecimal).toString();
			if (flag)
				s = (new StringBuilder(String.valueOf(setting.getCurrencySign()))).append(s).toString();
			if (flag1)
				s = (new StringBuilder(String.valueOf(s))).append(setting.getCurrencyUnit()).toString();
			return new SimpleScalar(s);
		} else {
			return null;
		}
	}
}
